<?php

require_once 'util/class.daofactory.php';

class TagListService {
	
	public function getList($tagId, $pageIndex, $sinceNoteId) {
		$result = array();
		if(!is_int($tagId) || $tagId<0
				|| !is_int($pageIndex) || $pageIndex<0
				|| !is_int($sinceNoteId) || $sinceNoteId<0 ) {
			$result['status']=Constants::$ERROR_INVALID_ARGS;
			return $result;
		}
		
		
		// step1, get id list from tag
		global $tagListDao;
		$tagList = $tagListDao->getTagList($tagId, Constants::$TAGLIST_PAGE_SIZE,
				$sinceNoteId);
		
		if($tagList==null || count($tagList)==0) {
			$result['status']=Constants::$SUCCESS;
			$result['data']=array('pageIndex'=>$pageIndex, 'notes'=>array());
			return $result;
		}
		
		// step2, get note info and user info for each id
		$notesList = array();
		$noteInfo=null;
		foreach ($tagList as $tagItem) {
			$noteInfo = $this->getDisplayedNote($tagItem['nid']);
			if(!$noteInfo)
				continue;
			$noteInfo['type']=0;
			$notesList[]=$noteInfo;
		}
		
		// return the data
		$result['status']=Constants::$SUCCESS;
		$result['data']=array('pageIndex'=>$pageIndex, 'notes'=>$notesList);
		return $result;
	}
	
	private function getDisplayedNote($noteId) {
		global $noteDao;
		$noteInfo = $noteDao->getNoteForRead($noteId);
		if(!$noteInfo)
			return null;
		
		// get poster display user info
		$postUserInfo = $this->getDisplayUserInfo($noteInfo['uid']);
		$noteInfo['nick']=$postUserInfo['nick'];
		$noteInfo['avatar']=$postUserInfo['avatar'];
		return $noteInfo;
	}
	
	private function getDisplayUserInfo($userId) {
		global $userDao;
		$userInfo = $userDao->getUserDisplayInfo($userId);
		if($userInfo) {
			if(!array_key_exists('avatar', $userInfo))
				$userInfo['avatar']=Constants::$DEFAULT_AVATAR;
			return $userInfo;
		}
			
		return Constants::$DEFAULT_USER_DISPLAY_INFO;
	}
	
}